<template>
    <div class="box">
        <div>
            <h1>登录页面</h1>
        </div>
        <div>
             <el-form
                ref="ruleFormRef"
                style="max-width: 600px"
                :model="ruleForm"
                :rules="rules"
                label-width="auto"
                class="demo-ruleForm"
                :size="formSize"
                status-icon
            >
               <el-form-item label="手机号" required>
                  <el-col :span="11">
                    <el-form-item prop="userMobile">
                         <el-input v-model="ruleForm.userMobile" />
                    </el-form-item>
                  </el-col>
                  <el-col class="text-center" :span="2">
                    <span class="text-gray-500"></span>
                  </el-col>
                  <el-col :span="11">
                    <el-form-item>
                        <el-button @click="codeByMobile" :disabled="disabled">{{ disabled ? "剩余" + timeDate : "获取手机验证码" }}</el-button>
                    </el-form-item>
                  </el-col>
                </el-form-item>
                <el-form-item label="手机验证码" prop="userCode">
                <el-input v-model="ruleForm.userCode" />
                </el-form-item>
                <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    登 录
                </el-button>
                <el-button @click="resetForm(ruleFormRef)">取 消</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ComponentSize, ElMessage, FormInstance, FormRules } from 'element-plus'
import { userLogin, getCode, mobileLogin } from '../api/api'
import { useRouter } from 'vue-router';

const router = useRouter();
const disabled = ref(false)
const timeDate = ref(60);
interface RuleForm {
    userName: string,
    userPass: string,
    userMobile: string,
    userCode: string,
}
const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
    userName: '',
    userPass: '',
    userMobile: '',
    userCode: '',
})
const codeByMobile = () => {
  disabled.value = true;
  let times = setInterval(() => {
    if (timeDate.value < 0) {
      disabled.value = false;
      timeDate.value = 60;
      clearInterval(times)
    } else {
      timeDate.value --;
    }
  }, 1000);
  getCode(ruleForm.userMobile).then(res => {
    if (res.data.code == 200) {
      ElMessage.success("发送成功");
    } else {
      ElMessage.success("发送失败")
      disabled.value = false;
      timeDate.value = 60;
      clearInterval(times)
    }
  })
}
const locationOptions = ['Home', 'Company', 'School']
const rules = reactive<FormRules<RuleForm>>({
  userName: [
    { required: true, message: '请输入用户账号', trigger: 'blur' },
    { min: 3, max: 10, message: '长度不能小于 3 位或不能大于 10 位', trigger: 'blur' },
  ],
   userPass: [
    { required: true, message: '请输入用户密码', trigger: 'blur' },
    { min: 6, max: 11, message: '长度不能小于 6 位或不能大于 11 位', trigger: 'blur' },
  ],
   userMobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/, message: '手机号格式不对', trigger: 'blur' },
  ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      mobileLogin(ruleForm).then(res => {
        if (res.data.code == 200) {
            ElMessage.success("登录成功")
            let user = res.data.data
            let token = user.token;
            window.sessionStorage.setItem('token', token)
            window.sessionStorage.setItem('user', JSON.stringify(user))
            router.push("/home")
        } else {
            ElMessage.error("登录失败")
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}))

</script>

<style scoped>

</style>